#' Linear Regression Function
#'
#' This function performs a simple linear regression.
#'
#' @param formula A formula object, specifying the model, e.g. y ~ x.
#' @param data An optional data frame containing the variables in the formula.
#' @return An object of class 'lin_reg' containing the regression coefficients.
#' @examples
#' library(mylin2024141054)
#' x <- rnorm(100)
#' y <- 20 * x + 23 + rnorm(100)
#' data <- data.frame(x = x, y = y)
#' model <- lin_reg(y ~ x, data = data)
#' save(model, data, file = "my_model_file.rda")
#'
#'
#'
#'
#' 在另外一台电脑上，
#' 本地安装好mylin2024141054扩展包之后，
#' 通过library(mylin2024141054);
#' load("my_model_file.rda");
#' predict(model, 1:10)，
#' 能得到相应的预测预测结果。
#' 示例：
#'
#' library(mylin2024141054)
#' data(my_model_file)  # 这将加载模型对象，确保其名称为 'model'
#' predictions <- predict(model, 1:10)
#' plot(data$x, data$y, main = "Actual vs Predicted", xlab = "x", ylab = "y")
#' points(data$x, predictions, col = "red", pch = 19)
#' legend("topright", legend = c("Actual", "Predicted"), col = c("black", "red"), pch = c(1, 19))
#' @export
#' @importFrom stats model.frame model.matrix model.response na.pass predict

lin_reg <- function(formula, data) {
  # 提取模型的响应变量和预测变量
  terms <- attr(terms(formula), "term.labels")
  y <- model.response(model.frame(formula, data))
  x <- model.matrix(formula, data)

  # 使用最小二乘法拟合模型
  beta <- solve(t(x) %*% x) %*% t(x) %*% y

  # 创建一个list来存储模型信息
  model <- list(beta = beta, x = x, y = y, terms = formula, call = match.call())
  class(model) <- "lin_reg"
  return(model)
}


